<template>
  <div class="friend-list-with-follow">
    <div v-for="friend in paginatedFriends" :key="friend.id || friend.email" class="friend-item">
      <!-- 左侧头像 -->
      <UserAvatarCard
        :avatar="friend.avatar || ''"
        :username="friend.name || friend.username || ''"
        :email="friend.email"
        :size="48"
      />
      
      <!-- 中间用户名 -->
      <div class="friend-info">
        <div class="friend-name">{{ friend.name || friend.username || '' }}</div>
        <div class="friend-email">{{ friend.email }}</div>
      </div>
      
      <!-- 右侧关注按钮 -->
      <a-button 
        :type="getButtonType(friend)"
        :loading="friend.loading"
        @click="onFollowClick(friend)"
        class="follow-button"
      >
        {{ getFollowText(friend) }}
      </a-button>
    </div>
    
    <!-- 分页器 -->
    <a-pagination
      v-if="friends.length > pageSize"
      v-model:current="currentPage"
      :pageSize="pageSize"
      :total="friends.length"
      :showSizeChanger="false"
      :showQuickJumper="false"
      :showTotal="(total, range) => `共 ${total} 个好友`"
      style="margin-top: 16px; text-align: center"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { message, Modal } from 'ant-design-vue'
import UserAvatarCard from './UserAvatarCard.vue'
import { getFollowStatus, follow, unfollow } from '@/api/user'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

const props = defineProps({
  friends: {
    type: Array,
    default: () => []
  },
  pageSize: {
    type: Number,
    default: 10
  }
})

const currentPage = ref(1)
const friendsWithStatus = ref([])

// 分页后的好友列表
const paginatedFriends = computed(() => {
  const start = (currentPage.value - 1) * props.pageSize
  const end = start + props.pageSize
  return friendsWithStatus.value.slice(start, end)
})

// 获取关注状态文本
function getFollowText(friend) {
  if (userStore.userStats.email === friend.email) {
    return '自己'
  }
  if (!friend.following) return '关注'
  if (friend.following && !friend.followers) return '已关注'
  if (friend.following && friend.followers) return '互相关注'
  return '关注'
}

// 获取按钮类型
function getButtonType(friend) {
  if (userStore.userStats.email === friend.email) {
    return 'default'
  }
  if (!friend.following) return 'primary'
  return 'default'
}

// 获取单个好友的关注状态
async function fetchFriendStatus(friend) {
  if (userStore.userStats.email === friend.email) {
    return { following: false, followers: false }
  }
  
  try {
    const res = await getFollowStatus(friend.email)
    return {
      following: res.following,
      followers: res.followers
    }
  } catch (error) {
    console.error('获取关注状态失败:', error)
    return { following: false, followers: false }
  }
}

// 关注/取消关注
async function onFollowClick(friend) {
  if (userStore.userStats.email === friend.email) {
    return
  }
  
  friend.loading = true
  
  try {
    if (!friend.following) {
      // 关注
      const res = await follow(friend.email)
      message.success(res.message)
      friend.following = true
    } else {
      // 取消关注
      Modal.confirm({
        title: '取消关注',
        content: '确定要取消关注该用户吗？',
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          try {
            const res = await unfollow(friend.email)
            message.success(res.message)
            friend.following = false
            friend.followers = false
          } catch (error) {
            message.error(error)
          }
        }
      })
    }
  } catch (error) {
    message.error(error)
  } finally {
    friend.loading = false
  }
}

// 初始化好友状态
async function initializeFriendsStatus() {
  friendsWithStatus.value = await Promise.all(
    props.friends.map(async (friend) => {
      const status = await fetchFriendStatus(friend)
      return {
        ...friend,
        following: status.following,
        followers: status.followers,
        loading: false
      }
    })
  )
}

// 监听好友列表变化
watch(() => props.friends, () => {
  initializeFriendsStatus()
}, { deep: true })

onMounted(() => {
  initializeFriendsStatus()
})
</script>

<style scoped>
.friend-list-with-follow {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  transition: box-shadow 0.2s;
}

.friend-item:hover {
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.friend-info {
  flex: 1;
  margin-left: 16px;
  display: flex;
  flex-direction: column;
}

.friend-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.friend-email {
  font-size: 12px;
  color: #888;
}

.follow-button {
  min-width: 80px;
  margin-left: 16px;
}

.follow-button[disabled] {
  cursor: not-allowed;
}
</style>